package com.yuexunit.mobilenurse.module.BloodCollection.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.BloodCollection.adapter.BloodCollectionAdapter;
import com.yuexunit.mobilenurse.module.BloodCollection.model.impl.BloodCollectionModel;
import com.yuexunit.mobilenurse.module.BloodCollection.presenter.IBloodCollectionPresenter;
import com.yuexunit.mobilenurse.module.BloodCollection.presenter.impl.BloodCollectionPresenter;
import com.yuexunit.mobilenurse.module.BloodCollection.ui.view.IBloodCollectionView;
import com.yuexunit.mobilenurse.module.PatientDetail.bean.Collectinfo;
import com.yuexunit.mobilenurse.scan.Idata.ScannerInerface;
import com.yuexunit.mobilenurse.widget.LoadingDialog;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/7/11 0011.
 */

public class Act_BloodCollection_Idata extends KJActivity implements IBloodCollectionView {
    @Bind(R.id.bloodcollection_list)
    ListView bloodcollectionList;

    BaseAdapter adapter;
    private LoadingDialog dialog;

    ArrayList<Collectinfo> collectinfos = new ArrayList<Collectinfo>();

    IBloodCollectionPresenter presenter;

    ScannerInerface scanner;
    IntentFilter intentFilter;
    BroadcastReceiver scanReceiver;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_bloodcollection);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        dialog = new LoadingDialog(aty);
        presenter = new BloodCollectionPresenter(new BloodCollectionModel(),this);
        adapter = new BloodCollectionAdapter(bloodcollectionList, collectinfos, R.layout.item_bloodcollection);
        bloodcollectionList.setAdapter(adapter);
    }

    @Override
    public void onResume(){
        super.onResume();
        initScanner();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onStop(){
        super.onStop();
        finishScanner();
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        finishScanner();
    }

    private void initScanner(){
        scanner = new ScannerInerface(this);
        scanner.open();	//打开扫描头上电   scanner.close();//打开扫描头下电
        scanner.enablePlayBeep(true);//是否允许蜂鸣反馈
        scanner.enableFailurePlayBeep(true);//扫描失败蜂鸣反馈
        scanner.enablePlayVibrate(true);//是否允许震动反馈
        scanner.setCharSetMode(4);//设置解码方式
        //		scanner.enablShowAPPIcon(false);//是否允许显示iscan的应用程序图标   部分设备 调用出现异常，建议不要调用该功能
        //		scanner.enablShowNoticeIcon(false);//是否允许显示iscan通知栏图标     部分设备 调用出现异常，建议不要调用该功能
        scanner.enableAddKeyValue(1);/**附加无、回车、Teble、换行*/
        scanner.timeOutSet(2);//设置扫描延时2秒
        scanner.intervalSet(10); //设置连续扫描间隔时间
        scanner.lightSet(false);//关闭右上角扫描指示灯
        scanner.enablePower(true);//省电模式
        //		scanner.addPrefix("AAA");//添加前缀
        //		scanner.addSuffix("BBB");//添加后缀
        //		scanner.interceptTrimleft(2); //截取条码左边字符
        //		scanner.interceptTrimright(3);//截取条码右边字符
        //		scanner.filterCharacter("R");//过滤特定字符
        //		scanner.SetErrorBroadCast(true);//扫描错误换行
        //      scanner.resultScan();//恢复iScan默认设置

        scanner.lockScanKey();
        //锁定设备的扫描按键,通过iScan定义扫描键扫描，用户也可以自定义按键。
//		scanner.unlockScanKey();
        //释放扫描按键的锁定，释放后iScan无法控制扫描按键，用户可自定义按键扫描。

        /**设置扫描结果的输出模式，参数为0和1：
         * 0为模拟输出（在光标停留的地方输出扫描结果）；
         * 1为广播输出（由应用程序编写广播接收者来获得扫描结果，并在指定的控件上显示扫描结果）
         * 这里采用接收扫描结果广播并在TextView中显示*/
        scanner.setOutputMode(1);

        //扫描结果的意图过滤器的动作一定要使用"android.intent.action.SCANRESULT"
        intentFilter = new IntentFilter(AppConfig.IDATA);
        //注册广播接受者
        scanReceiver = new ScannerResultReceiver();
        registerReceiver(scanReceiver, intentFilter);
    }

    /**
     * 结束扫描
     */
    private void finishScanner(){
        scanner.scan_stop();
        //    	 scanner.close();	//关闭iscan  非正常关闭会造成iScan异常退出
        try {
            unregisterReceiver(scanReceiver);	//反注册广播接收者
        } catch (IllegalArgumentException e) {

        }
        scanner.continceScan(false);
    }


    @OnClick({R.id.bloodcollection_img_back, R.id.bloodcollection_img_search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bloodcollection_img_back:
                finish();
                break;
            case R.id.bloodcollection_img_search:
                Intent intent = new Intent(aty,Act_BloodCollection_Serach.class);
                startActivity(intent);
                break;
        }
    }


    /**
     * 扫描结果的广播接收者
     */
    private class ScannerResultReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(AppConfig.IDATA)){
                //获取扫描结果
                final String mBarcodeData = intent.getStringExtra("value");
                if (!mBarcodeData.equals("")) {
                    if(!mBarcodeData.equals(""))
                    {
                        if(mBarcodeData.length() == Integer.valueOf(PreferenceHelper.readString(aty, AppConfig.JCI_INFO, AppConfig.JCI_CX_RULE))) {
                            dialog.show();
                            presenter.collect("", mBarcodeData, PreferenceHelper.readString(aty, AppConfig.NURSE_INFO, AppConfig.NURSE_LOGID));
                        }
                        else {
                            Toast.makeText(aty, "条码无效!", Toast.LENGTH_LONG).show();
                        }
                    }
                }
            }
        }
    }

    @Override
    public void collectSend(Boolean isSuccess ,Collectinfo collectinfo) {
        if(isSuccess)
        {
            if(collectinfo != null) {
                collectinfos.add(collectinfo);
                adapter.notifyDataSetChanged();
            }
            else {
                ViewInject.toast("该标本已发送");
            }
        }
        else {
            ViewInject.toast("发送失败");
        }
        dialog.dismiss();
    }
}
